package cn.sciento.starter.keyencrypt.mvc;

import cn.sciento.starter.keyencrypt.core.Encrypt;
import cn.sciento.starter.keyencrypt.core.EncryptContext;
import cn.sciento.starter.keyencrypt.core.IEncryptionService;
import cn.sciento.starter.keyencrypt.util.EncryptUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver;

public class EncryptPathVariableMethodArgumentResolver extends PathVariableMethodArgumentResolver {
  IEncryptionService encryptionService;
  
  public EncryptPathVariableMethodArgumentResolver(IEncryptionService encryptionService) {
    this.encryptionService = encryptionService;
  }
  
  @Nullable
  protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
    Object value = super.resolveName(name, parameter, request);
    Encrypt encrypt = parameter.getParameterAnnotation(Encrypt.class);
    if (EncryptContext.isEncrypt() && value != null && value instanceof String && parameter
      .hasParameterAnnotation(Encrypt.class) &&
      !EncryptUtils.ignoreValue(encrypt, (String)value))
      value = this.encryptionService.decrypt((String)value, encrypt.value(), encrypt.ignoreUserConflict()); 
    return value;
  }
}
